﻿using BoilerplateWPF.Models;
using BoilerplateWPF.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace BoilerplateWPF.Views
{
    /// <summary>
    /// LoginView.xaml 的交互逻辑
    /// </summary>
    public partial class LoginView : Window
    {
        // 用于控制动画的计时器
        private DispatcherTimer animationTimer;
        // 存储所有粒子及其运动数据
        private List<ParticleInfo> particles = new List<ParticleInfo>();

        public LoginView()
        {
            var viewModel = new LoginViewModel(); // 先创建 ViewModel
            this.DataContext = viewModel; // 设置 DataContext
            InitializeComponent(); // 然后初始化组件（这样绑定就能找到 DataContext）

            // 订阅事件
            viewModel.LoginSuccessful += OnLoginSuccessful;
            this.Loaded += Window_Loaded; // 窗口加载完成后初始化粒子

            // 在窗口关闭时取消订阅，避免内存泄漏
            this.Closed += (s, e) =>
            {
                viewModel.LoginSuccessful -= OnLoginSuccessful;
                this.Loaded -= Window_Loaded; // 同时取消Loaded事件订阅（虽然不是必须，但推荐）
            };
        }

        private void OnLoginSuccessful(UserModel user)
        {
            ShellView shellView = new ShellView(user);
            shellView.Show();
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeParticles();
            StartAnimation();
        }

        private void InitializeParticles()
        {
            Random rand = new Random();
            ParticleCanvas.Children.Clear(); // 清空原有粒子
            particles.Clear();

            // 创建21个粒子
            for (int i = 0; i < 21; i++)
            {
                // 1. 创建椭圆（粒子）
                Ellipse ellipse = new Ellipse
                {
                    Width = rand.Next(3, 10), // 随机大小 3-10
                    Height = rand.Next(3, 10),
                    Fill = new SolidColorBrush(Color.FromArgb(
                        (byte)rand.Next(80, 180), // 随机透明度 (80-180)
                        255, 255, 255)),          // 白色光点
                    Effect = new BlurEffect { Radius = rand.Next(2, 6) } // 随机模糊度
                };

                // 2. 随机初始位置（Within the polygon area）
                double left = rand.Next(0, (int)(ParticleCanvas.ActualWidth - ellipse.Width));
                double top = rand.Next(0, (int)(ParticleCanvas.ActualHeight - ellipse.Height));
                Canvas.SetLeft(ellipse, left);
                Canvas.SetTop(ellipse, top);

                // 3. 添加到Canvas
                ParticleCanvas.Children.Add(ellipse);

                // 4. 存储粒子信息（用于动画）
                particles.Add(new ParticleInfo
                {
                    Shape = ellipse,
                    SpeedX = (rand.NextDouble() - 0.5) * 0.3, // 随机X速度 (-0.15 to 0.15)
                    SpeedY = (rand.NextDouble() - 0.5) * 0.2, // 随机Y速度 (-0.1 to 0.1)
                    OriginalOpacity = ellipse.Opacity
                });
            }
        }

        // 开始动画
        private void StartAnimation()
        {
            animationTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(30) // 约30FPS
            };
            animationTimer.Tick += AnimationTimer_Tick;
            animationTimer.Start();
        }

        // 每一帧更新粒子位置和透明度
        private void AnimationTimer_Tick(object sender, EventArgs e)
        {
            for (int i = 0; i < particles.Count; i++)
            {
                ParticleInfo particle = particles[i];
                Ellipse ellipse = particle.Shape;

                // 获取当前位置
                double currentLeft = Canvas.GetLeft(ellipse);
                double currentTop = Canvas.GetTop(ellipse);

                // 计算新位置
                double newLeft = currentLeft + particle.SpeedX;
                double newTop = currentTop + particle.SpeedY;

                // 边界检查（让粒子在Canvas范围内移动）
                if (newLeft < 0 || newLeft > ParticleCanvas.ActualWidth - ellipse.Width)
                    particle.SpeedX *= -1; // 反向
                else
                    Canvas.SetLeft(ellipse, newLeft);

                if (newTop < 0 || newTop > ParticleCanvas.ActualHeight - ellipse.Height)
                    particle.SpeedY *= -1; // 反向
                else
                    Canvas.SetTop(ellipse, newTop);

                // (可选) 添加轻微的透明度闪烁，模拟星光闪烁
                //ellipse.Opacity = particle.OriginalOpacity * (0.8 + 0.2 * Math.Sin(DateTime.Now.Millisecond * 0.01 + i));
            }
        }

        // 辅助类，存储粒子动态信息
        private class ParticleInfo
        {
            public Ellipse Shape { get; set; }
            public double SpeedX { get; set; }
            public double SpeedY { get; set; }
            public double OriginalOpacity { get; set; }
        }

        /// <summary>
        /// 鼠标按住可拖动 全位置
        /// </summary>
        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
    }
}
